package com.gjy.concurrency.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-12-13 13:50:12
 */
public class CyclicBarrierTest {

    private static final Logger logger = LoggerFactory.getLogger(CyclicBarrierTest.class);

    private static final CyclicBarrier CYCLIC_BARRIER = new CyclicBarrier(2,
            () -> logger.info("执行完毕"));

    public static void main(String[] args) {

        ExecutorService pool = Executors.newFixedThreadPool(3);
        pool.execute(() -> {
            try {
                logger.info("--poo1");
                TimeUnit.SECONDS.sleep(1);
                CYCLIC_BARRIER.await();
                logger.info("poo1--");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        pool.execute(() -> {
            try {
                logger.info("--poo2");
                TimeUnit.SECONDS.sleep(1);
                CYCLIC_BARRIER.await();
                logger.info("poo2--");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });

        pool.execute(() -> {
            try {
                logger.info("--poo3");
                TimeUnit.SECONDS.sleep(1);
                CYCLIC_BARRIER.await();
                logger.info("poo3--");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        pool.execute(() -> {
            try {
                logger.info("--poo4");
                TimeUnit.SECONDS.sleep(1);
                CYCLIC_BARRIER.await();
                logger.info("poo4--");
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        });
        pool.shutdown();
    }
}
